package com.gitee.beiding.timer;


import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

//持久化单元
class Dao {

    private TaskRepository taskRepository;

    Dao(TaskRepository taskRepository) {
        this.taskRepository = taskRepository;
    }

    //在内存中的任务
    private static final Map<String, Task> inMemory = new ConcurrentHashMap<String, Task>();

    //删除任务和持久化单元上的任务
    boolean remove(String id) {
        this.taskRepository.deleteById(id);
        Task remove = inMemory.remove(id);
        if (remove != null) {
            return remove.setCancel();
        }
        return true;
    }

    String save(Task task) {
        taskRepository.save(task);
        return task.getId();
    }

    //前等后不等
    Set<Task> get(long start, long end) {
        Set<Task> tasks = taskRepository.getRange(start, end);
        Set<Task> r = new HashSet<>();
        for (Task task : tasks) {
            if (!inMemory.containsKey(task.getId())) {
                r.add(task);
                inMemory.put(task.getId(), task);
            }
        }
        return r;
    }

    void flagInMemory(Task task) {
        inMemory.put(task.getId(), task);
    }
}
